/*
 * @文件描述:管理和PC的连接，使用socket接口或者其他什么接口
 * @版本:
 * @作者:周晨阳
 * @Date:2021-11-01 16:23:01
 */
#include "connection.h"
#include "systemInfo.h"
#include <QtNetwork>
#include <QtWidgets>

QTcpSocket *clientConnection;
QTcpServer *mp_TCPServer;
CONNECT_STATE state = DISCONNECT;
static MainWindow *view;
void Connection::init(MainWindow *window)
{
    view = window;
    mp_TCPServer = new QTcpServer();
    if (!mp_TCPServer->listen(QHostAddress::Any, 6665))
    {
        qDebug() << "Error server";
        return;
    }
    connect(mp_TCPServer, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
}
void Connection::acceptConnection()
{
    qDebug() << "new connection";
    clientConnection = mp_TCPServer->nextPendingConnection();
    connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readClient()));
    state = OK;
}
void Connection::readClient()
{
    QString str = clientConnection->readAll();
    qDebug() << "str:" << str;
    this->analysisString(str);
}
CONNECT_STATE Connection::getConnecState(void)
{
    return (CONNECT_STATE)0;
}
void Connection::analysisString(QString string)
{
    QStringList commandList = string.split(";");

    for (int i = 0; i < commandList.length()-1; i++)
    {
        QStringList list = commandList[i].split('=');
        DATA_TYPE name = (DATA_TYPE)(list[0].toInt());
        int value = list[1].toInt();
        qDebug() << "name:" << name;
        qDebug() << "value:" << value;

        switch (name)
        {
        case MEM:
            /* code */
            view->onViewSetMemory(value);

            break;
        case CPU:
            view->onViewChangeRelValue(value);

            break;
        case DISK:

            /* code */
            view->onViewSetDisk(value);

            break;
        }
    }
}
